package handlers

import (
	"errors"
	"strconv"

	"sales-web/server/dal"

	"github.com/gin-gonic/gin"
)

func (h *Handler) QueryCountry(c *gin.Context) {
	var result []dal.Country
	var count int64
	err := h.dbc.Find(&result).Count(&count).Error

	// err = h.dbc.Debug().Find(result).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, result)
}

func (h *Handler) CreateCountry(c *gin.Context) {
	var request dal.Country
	err := c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	if request.Name == "" || request.LimitPrice <= 0 {
		SendErrResp(c, 400, errors.New("invalid input"))
		return
	}
	var count int64
	err = h.dbc.Model(&dal.Country{}).Where("name = ?", request.Name).Count(&count).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	if count > 0 {
		SendErrResp(c, 400, errors.New("conutry exist"))
		return
	}
	err = h.dbc.Create(&request).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, request)
}

func (h *Handler) DeleteCountry(c *gin.Context) {
	idStr, _ := c.Params.Get("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var item dal.Country
	err = h.dbc.Where("id= ?", id).First(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	err = h.dbc.Delete(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}

	SendOkResp(c, "")
}

func (h *Handler) UpdateCountry(c *gin.Context) {
	idStr, _ := c.Params.Get("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var request dal.Country
	err = c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var item dal.Country
	err = h.dbc.Where("id= ?", id).First(&item).Error
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	user := GetCurrentUser(c)
	if user.Role != "super_admin" {
		SendOkResp(c, "")
		return
	}

	item.LimitPrice = request.LimitPrice
	item.CostPrice = request.CostPrice
	item.Name = request.Name
	item.Code = request.Code
	item.Comment = request.Comment
	err = h.dbc.Save(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, "")
}
